import { Empty, Spin } from 'antd';
import { useEffect, useState } from 'react';
import TreeList from '../../../FunPermission/components/Permission/Tree';
import '../../../style.less';
import { action } from '../../../FunPermission/components/Model';
import {
  getModule,
  getModel,
  getUserModelPerm,
  addModelUserPerm,
  delModelUserPerm,
} from '../../../service';
import { TextWidget } from '@inbiz/react';

function Model(props) {
  const { selectMember, permConfig, appId, containerHeight } = props;
  const { MemberId, MemberType } = selectMember;

  const [modelData, $modelData] = useState([]); //模型数据
  const [selectModel, $selectModel] = useState([]); // 选中模型
  const [modelFields, $modelFields] = useState([]); //动作和属性
  const [permData, $permData] = useState([]); //所有权限列表
  const [modelChecked, $modelChecked] = useState({ checked: [], halfChecked: [] }); //模型权限勾选
  const [allFieldChecked, $allFieldChecked] = useState([]); //所有模型字段勾选
  const [fieldChecked, $fieldChecked] = useState([]); //当前渲染模型字段勾选

  const [loadding1, $loadding1] = useState(false);
  //获取模型分组
  useEffect(() => {
    getModuleList();
  }, []);

  //获取动作或属性
  useEffect(() => {
    $modelFields([]);
    if (selectModel.length) {
      $modelFields((oringe) => {
        return getModelFields(selectModel);
      });
      $fieldChecked((origin) => {
        return allFieldChecked.filter((item) => item.split('&')[0] == selectModel[0]);
      });
    }
  }, [selectModel]);

  // 获取当前站点下的模型分组
  const getModuleList = () => {
    $loadding1(true);
    getModule({
      appId,
    }).then((res) => {
      $loadding1(false);
      $modelData(formatData(res.List));
    });
  };

  //查询选中成员的模型权限
  useEffect(() => {
    $modelData([]);
    $selectModel([]);
    $modelFields([]);
    $permData([]);
    $modelChecked({ checked: [], halfChecked: [] });
    $allFieldChecked([]);
    $fieldChecked([]);
    getModuleList();
  }, [MemberId]);

  // 数据格式化
  const formatData = (list, child?, key?) => {
    //child:true为子级
    if (list?.length) {
      list = list.map((item) => {
        let parm = {
          ...item,
          key: key ? `${item.modelkey}&${item[key]}&0` : item.Key || item.ModelKey,
          isLeaf: child ? true : false,
          selectable: child ? true : false,
        };
        return parm;
      });
      return list;
    } else {
      return [];
    }
  };
  // 异步加载数据和权限
  const onLoadData = (treeNode) => {
    return new Promise<void>((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      // 获取权限
      getPermList(treeNode.props.dataRef.ID);
      getModel({ moduleId: treeNode.props.dataRef.ID }).then((res) => {
        if (res) {
          const data = formatData(res.List, true).filter((item) => {
            return item.PublishState == 1;
          });
          treeNode.props.dataRef.children = data;
          $modelData(updateTreeData(modelData, data, treeNode.props.eventKey));
          resolve();
        }
      });
    });
  };
  const updateTreeData = (list, children, key) => {
    return list.map((node) => {
      if (node.key === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  };

  // 根据选中模型获取模型字段
  const getModelFields = (modelkey) => {
    let list = [];
    modelData?.map((item) => {
      if (item.children?.length) {
        item.children.map((item1) => {
          if (item1.ModelKey == modelkey[0]) {
            list = item1.Fields.map((item2) => {
              return {
                ...item2,
                modelkey: modelkey[0],
              };
            });
          }
        });
      }
    });
    // 获取已发布的模型字段
    list = formatData(list, true, 'Name').filter((item) => {
      return item.PublishState == 1;
    });
    let newAction = {
      ...action,
      children: action.children.map((item) => {
        return {
          ...item,
          key: `${modelkey[0]}&${item.key}`,
        };
      }),
    };
    return [
      newAction,
      // {
      //   Name: '属性',
      //   key: 'fields',
      //   selectable: false,
      //   children: list,
      // }
    ];
  };
  const getPermList = (moduleId, isEdit?) => {
    let parm = {
      memberId: MemberId,
      memberType: MemberType,
      moduleId,
    };
    getUserModelPerm(parm).then((res) => {
      if (res) {
        let fieldPermList = [];
        let checked = [],
          halfChecked = [];
        res.map((item) => {
          let allPerm = true;
          let hasperm = false;
          item.ButtonChildren?.map((item1) => {
            if (item1.PermissionValue == 0) {
              allPerm = false;
            } else {
              hasperm = true;
              fieldPermList.push(`${item.ModelKey}&${item1.ParaName}&1`);
            }
          });
          // item.FiledChildren?.map(item2 => {
          //   if (item2.PermissionValue == 0) {
          //     allPerm = false;
          //   } else {
          //     hasperm = true;
          //     fieldPermList.push(`${item.ModelKey}&${item2.ParaName}&0`)
          //   }
          // })
          if (allPerm) {
            checked.push(item.ModelKey);
          } else {
            if (hasperm) {
              halfChecked.push(item.ModelKey);
            }
          }
        });
        $permData((origin) => {
          if (isEdit) {
            let newOrigin = origin.map((item) => {
              const newItem = res?.filter((item2) => item.ModelKey == item2.ModelKey);
              if (newItem.length) {
                return {
                  ...newItem[0],
                  moduleId,
                };
              } else {
                return {
                  ...item,
                };
              }
            });
            return newOrigin;
          } else {
            return [
              ...origin,
              ...res.map((item) => {
                return {
                  ...item,
                  moduleId,
                };
              }),
            ];
          }
        });
        $modelChecked((origin) => {
          let otherChecked = [];
          let oterHalfChecked = [];
          let otherPermData = permData.filter((item) => item.moduleId != moduleId);
          otherPermData?.map((item1) => {
            if (origin?.checked?.indexOf(item1.ModelKey) != -1) {
              otherChecked.push(item1.ModelKey);
            }
            if (origin?.halfChecked?.indexOf(item1.ModelKey) != -1) {
              oterHalfChecked.push(item1.ModelKey);
            }
          });
          let newOrigin = isEdit
            ? {
                checked: [...otherChecked, ...checked],
                halfChecked: [...oterHalfChecked, ...halfChecked],
              }
            : {
                checked: [...origin.checked, ...checked],
                halfChecked: [...origin.halfChecked, ...halfChecked],
              };
          return newOrigin;
        });
        let oterfieldPermList = [];
        let otherPermData = permData.filter((item) => item.moduleId != moduleId);
        otherPermData.map((item) => {
          item.ButtonChildren?.map((item1) => {
            if (item1.PermissionValue != 0) {
              oterfieldPermList.push(`${item.ModelKey}&${item1.ParaName}&1`);
            }
          });
        });
        $allFieldChecked((origin) => {
          let newOrigin = isEdit
            ? [...oterfieldPermList, ...fieldPermList]
            : [...origin, ...fieldPermList];
          return newOrigin;
        });
        $fieldChecked((origin) => {
          let newOrigin = isEdit
            ? [
                ...oterfieldPermList.filter((item) => item.split('&')[0] == selectModel[0]),
                ...fieldPermList.filter((item) => item.split('&')[0] == selectModel[0]),
              ]
            : [...origin, ...fieldPermList.filter((item) => item.split('&')[0] == selectModel[0])];
          return newOrigin;
        });
      }
    });
  };
  const onModelCheck = (checkedKeys, e) => {
    let list = [];
    if (e.checked) {
      list = checkedKeys.checked.filter((item) => {
        return modelChecked.checked.indexOf(item) === -1;
      });
      //批量添加权限
      editPerm(geteditKeys(list), 'add');
    } else {
      list = modelChecked.checked.filter((item) => {
        return checkedKeys.checked.indexOf(item) === -1;
      });
      //批量删除权限
      editPerm(geteditKeys(list), 'del');
    }
  };
  const onFieldCheck = (checkedKeys, e) => {
    if (e.checked) {
      //添加权限
      let addKeys = getAddKeys(checkedKeys, allFieldChecked);
      editPerm(addKeys, 'add');
    } else {
      //删除权限
      let delKeys = getDelKeys(checkedKeys, allFieldChecked, selectModel[0]);
      editPerm(delKeys, 'del');
    }
  };

  // 编辑权限
  const editPerm = (keys, editType) => {
    keys = keys.filter((item) => item.indexOf('&') != -1);
    let modelKey = keys[0].split('&')[0];
    let paramName = keys
      .map((item) => {
        return item.split('&')[1];
      })
      .filter((item) => item);
    let type = keys
      .map((item) => {
        return item.split('&')[2];
      })
      .filter((item) => item);
    let moduleId = '';
    modelData.map((item) => {
      item.children?.map((item1) => {
        if (item1.ModelKey == modelKey) {
          moduleId = item1.ModuleId;
        }
      });
    });
    if (!moduleId) return;
    let old = allFieldChecked;
    let newData = keys.filter((item) => item !== 'action' && item != 'fields');
    if (editType == 'add') {
      $allFieldChecked((origin) => {
        return [...origin, ...newData];
      });
      $fieldChecked((origin) => {
        return [...origin, ...newData];
      });
      addModelUserPerm({
        memberId: MemberId,
        memberType: MemberType,
        moduleId,
        modelKey,
        menuModelParamPermDto: paramName.map((item, i) => {
          return {
            type: type[i],
            paramName: item,
            permissionValue: 4,
          };
        }),
      }).then((res) => {
        if (!res) {
          $allFieldChecked((origin) => {
            return [...old];
          });
          $fieldChecked((origin) => {
            return [...old];
          });
        } else {
          getPermList(moduleId, true);
        }
      });
    } else {
      $allFieldChecked((origin) => {
        let list = [];
        origin.map((item) => {
          if (!newData.includes(item)) {
            list.push(item);
          }
        });
        return [...list];
      });
      $fieldChecked((origin) => {
        let list = [];
        origin.map((item) => {
          if (!newData.includes(item)) {
            list.push(item);
          }
        });
        return [...list];
      });
      let ids = getPermissionIds(modelKey, type, paramName);
      delModelUserPerm({
        modelKey,
        memberType: MemberType,
        memberId: MemberId,
        permissionFiledIds: ids.permissionFiledIds,
        permissionButtonIds: ids.permissionButtonIds,
      }).then((res) => {
        if (!res) {
          $allFieldChecked((origin) => {
            return [...old];
          });
          $fieldChecked((origin) => {
            return [...old];
          });
        } else {
          getPermList(moduleId, true);
        }
      });
    }
  };
  // 根据key获取权限id
  const getPermissionIds = (modelKey, type, paramName) => {
    let permissionFiledIds = [];
    let permissionButtonIds = [];
    permData.map((item) => {
      if (item.ModelKey == modelKey) {
        type.map((item3, index) => {
          if (item3 == 1) {
            item.ButtonChildren.map((item2) => {
              if (paramName[index] == item2.ParaName) {
                permissionButtonIds.push(item2.PermissionId);
              }
            });
          } else {
            // item.FiledChildren.map(item1 => {
            //   if (item1.ParaName == paramName[index]) {
            //     permissionFiledIds.push(item1.PermissionId)
            //   }
            // })
          }
        });
      }
    });
    return { permissionFiledIds, permissionButtonIds };
  };
  const getAddKeys = (arr1, arr2) => {
    let list = [];
    arr1.map((item) => {
      if (!arr2.includes(item)) {
        list.push(item);
      }
    });
    return list;
  };

  const getDelKeys = (arr1, arr2, modelKey) => {
    arr1 = arr1.filter((item) => item !== 'action' && item !== 'fields');
    let list = [];
    let arr3 = arr2.filter((item) => {
      if (item.split('&')[0] == modelKey) {
        return item;
      }
    });
    arr3.map((item) => {
      if (!arr1.includes(item)) {
        list.push(item);
      }
    });
    return list;
  };

  const geteditKeys = (modelKey) => {
    // 获取这个模型所有字段
    let allKeys = [];
    getModelFields(modelKey).map((item) => {
      if (item.children.length) {
        item.children.map((item2) => {
          allKeys.push(item2.key);
        });
      }
    });
    // 获取这个模型已选中的字段
    let checkedKeys = allFieldChecked.filter((item) => item.split('&')[0] == modelKey);
    let editKeys = allKeys.filter((item) => checkedKeys.includes(item) == false);
    if (editKeys.length) {
      return editKeys;
    } else {
      return allKeys;
    }
  };
  // 判断是否是ifream嵌套

  return (
    <div className={'main'} style={{ height: `calc(${containerHeight} - 144px)` }}>
      <div
        className={'userTreeList'}
        style={{ borderLeft: '1px solid #eee', width: '180px', flex: '0 0 180px' }}
      >
        {modelData.length ? (
          <TreeList
            defaultExpandedKeys={modelData[0]?.key}
            checkStrictly
            checkable
            key={MemberId}
            list={modelData}
            onLoadData={onLoadData}
            selectedKeys={selectModel}
            checkedKeys={modelChecked}
            treeClick={(arr: any) => $selectModel(arr)}
            treeCheck={onModelCheck}
          />
        ) : loadding1 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
      <div className={'lastTreeList'}>
        {modelFields.length ? (
          <TreeList
            checkable
            key={selectModel[0]}
            list={modelFields}
            treeClick={() => {}}
            checkedKeys={fieldChecked}
            treeCheck={onFieldCheck}
            defaultExpandAll={true}
          />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
    </div>
  );
}

export default Model;
